package com.example.exceldemo.controller;

import com.example.exceldemo.model.ApiResult;
import com.example.exceldemo.model.DocGenerationFile;
import com.example.exceldemo.model.DocGenerationTask;
import com.example.exceldemo.model.PageResult;
import com.example.exceldemo.model.dto.TaskQueryDTO;
import com.example.exceldemo.service.DocTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务查询和管理控制器
 */
@Slf4j
@Controller
@RequestMapping("/tasks")
@RequiredArgsConstructor
public class TaskController {
    
    private final DocTaskService taskService;
    
    /**
     * 查询任务状态
     *
     * @param taskId 任务ID
     * @return 任务状态
     */
    @GetMapping("/{taskId}")
    @ResponseBody
    public ApiResult<Map<String, Object>> getTaskStatus(@PathVariable("taskId") String taskId) {
        DocGenerationTask task = taskService.getTask(taskId);
        if (task == null) {
            return ApiResult.fail("任务不存在：" + taskId);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("taskId", task.getTaskId());
        result.put("status", task.getStatus());
        result.put("progress", task.getProgress());
        result.put("outputDir", task.getOutputDir());
        result.put("errorMessage", task.getErrorMessage());
        result.put("createTime", task.getCreateTime());
        result.put("completeTime", task.getCompleteTime());
        
        // 如果任务已完成，提供结果数据
        if (DocGenerationTask.TaskStatus.COMPLETED.name().equals(task.getStatus())) {
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("outputDir", task.getOutputDir());
            result.put("resultData", resultData);
        }
        
        return ApiResult.success(result);
    }
    
    /**
     * 任务管理页面
     */
    @GetMapping("/list")
    public String taskListPage() {
        return "task-list";
    }
    
    /**
     * 分页查询任务列表
     */
    @PostMapping("/page")
    @ResponseBody
    public ApiResult<PageResult<DocGenerationTask>> listTasks(@RequestBody TaskQueryDTO queryDTO) {
        PageResult<DocGenerationTask> pageResult = taskService.listTasks(queryDTO);
        return ApiResult.success(pageResult);
    }
    
    /**
     * 任务详情页面
     */
    @GetMapping("/detail/{taskId}")
    public String taskDetailPage(@PathVariable("taskId") String taskId, Model model) {
        DocGenerationTask task = taskService.getTask(taskId);
        if (task == null) {
            return "redirect:/tasks/list?error=任务不存在";
        }
        
        List<DocGenerationFile> files = taskService.listTaskFiles(taskId);
        
        model.addAttribute("task", task);
        model.addAttribute("files", files);
        
        return "task-detail";
    }
} 